<script setup>
import {inject, ref, watch} from 'vue'
import Upload from "@/components/Upload.vue";
import useLocationStore from "@/store/location.js";
import useUUIDUtil from '@/utils/uuid.js'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Link} from '@element-plus/icons-vue'
import usePatternStore from "@/store/pattern";
import useNatureSizeStore from "@/store/natureSize.js";
import defaultImg from '@/assets/pic-none.png'

const useNatureSize = useNatureSizeStore()
// 将默认图片导入
const imgRef = ref(defaultImg)
const useUUID = useUUIDUtil()
const useLocation = useLocationStore()
const usePattern = usePatternStore()
const visible = ref(usePattern.modal === "edit")
const props = defineProps({
  posObj: {
    type: Object,
    default: {}
  },
  rate: {
    type: Number,
    default: 1
  }
})
watch(() => usePattern.modal, (newVal) => {
  if (newVal === "edit") {
    visible.value = true
  } else {
    visible.value = false
  }
})
// submit包含了保存与更新操作
const submit = () => {
  // 保存
  if (!props.posObj.id) {
    console.log("新增", props.posObj)
    const data = {
      id: props.posObj.id,
      uuid: props.posObj.uuid,
      x: props.posObj.x,
      y: props.posObj.y,
      icon: props.posObj.icon,
      txt: props.posObj.txt,
      link: props.posObj.link
    }
    useLocation.addPosition(data)
  } else {
    //   更新
    console.log("更新", props.posObj)
    useLocation.updatePosition(props.posObj)
  }
  visible.value = false
}

const delPin = inject("delPin")
const delNode = (obj) => {
  // 缓存中删除
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    if(obj.id){
      await useLocation.deletePosition(obj)
    }
    // 调用方法，删除pin节点
    delPin(obj)
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
  });
}


// 第一、监听放大倍数；第二、监听鼠标的坐标
const rate = ref(0)
const mx = ref(0)
const my = ref(0)
watch(() => props.rate, (newVal) => {
  // newVal小于等于0.5的时候，就不再进行缩小
  rate.value = newVal
//   这个时候，mx和my的值应该是相对于图片的位置
  mx.value = props.posObj.x * rate.value / useNatureSize.getRate()
  my.value = props.posObj.y * rate.value / useNatureSize.getRate()
}, {
  immediate: true
})

const subImg = (img) => {
  props.posObj.icon = img
}
// 跳转
const jump = (link) => {
  if (link === null || link === '') {
    ElMessage.warning("链接地址为空")
    return
  }
  // 正则验证是否为url地址，验证.com .cn .net .org .edu .gov等等
  let reg = new RegExp("[a-zA-z]+://[^s]*");
  if (!reg.test(link)) {
    ElMessage.warning("链接地址格式错误,以http或者https开头")
    return
  } else {
    window.open(link)
  }
}
const omitStr = (str, len) => {
  if (str.length > len) {
    return str.substring(0, len) + "..."
  } else {
    return str
  }
}
const showText = ref(false)
const showTxt = () => {
  showText.value = !showText.value
}
</script>

<template>
  <div>
    <div v-if="!visible">
      <div :style="{ top: my+'px', left:mx+'px' }" @click="jump(props.posObj.link)"
           style="position:absolute; transform: translateX(-24px) translateY(-24px);border-radius: 50%;box-sizing: border-box;">
        <img @mouseover="showTxt" @mouseleave="showTxt" v-if="props.posObj.icon===null||props.posObj.icon===''"
             :src="imgRef"
             alt=""
             style="position:absolute;width:48px;height:48px;overflow:hidden;box-sizing: border-box;cursor: pointer;">
        <img @mouseover="showTxt" @mouseleave="showTxt" v-else :src="props.posObj.icon" alt=""
             style="position:absolute;width:48px;height:48px;overflow:hidden;box-sizing: border-box;cursor: pointer;">
      </div>

        <div class="img-container" :style="{ top: my+13+'px', left:mx+'px' }" v-show="showText">
          <div style="min-width: 48px; text-align: center;overflow: hidden;">
           <span style="font-weight: 800;font-size: 12px;">
            {{ omitStr(props.posObj.txt, 10) }}
          </span>
          </div>
        </div>
    </div>
    <div v-else>
      <div class="pin-container" :style="{ top: my+'px', left:mx+'px' }">
        <el-input v-model="props.posObj.txt" size="small" style="width:200px;" placeholder="Please input"
                  :disabled="!visible">
          <template #prepend class="prepend">
            <Upload @subImg="subImg" :icon="props.posObj.icon"></Upload>
          </template>
        </el-input>
        <div>
          <el-input v-show="visible" v-model="props.posObj.link" style="width:200px;" placeholder="跳转链接">
            <template #prepend class="prepend">
              <el-icon @click="jump(props.posObj.link)" style="cursor: pointer;" size="16" color="blue">
                <Link/>
              </el-icon>
            </template>
          </el-input>
        </div>

        <div style="margin-top:10px;">
          <el-button-group style="display: flex">
            <el-button type="primary" @click="submit">确定</el-button>
            <el-button type="danger" @click="delNode(props.posObj)">删除</el-button>
          </el-button-group>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-input-group--prepend .el-input-group__prepend) {
  width: 10px;
}


.pin-container {
  height: auto;
  background-color: whitesmoke;
  transform: translateX(-20px) translateY(10px);
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: start;
  align-items: center;
  border-radius: 8px;
  position: absolute;
  //定义一个三角形在左上角
  &:before {
    content: "";
    position: absolute;
    top: -20px;
    left: 10px;
    border: 10px solid transparent;
    border-bottom-color: whitesmoke;
  }
}

.img-container {
  height: auto;
  background-color: whitesmoke;
  transform: translateX(-20px) translateY(20px);
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  justify-content: start;
  align-items: center;
  border-radius: 8px;
  color: #512da8;
  position: absolute;
  //定义一个三角形在左上角
  &:before {
    content: "";
    position: absolute;
    top: -20px;
    left: 10px;
    border: 10px solid transparent;
    border-bottom-color: whitesmoke;
  }
}
</style>